<template>
  <div class="container">
    <div v-if="loading" class="loading">Loading...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else-if="article" class="article-detail">
      <div class="article-header">
        <span class="category">{{ article.category }}</span>
        <h1>{{ article.title }}</h1>
        <div class="meta">
          <span>By {{ article.author }}</span>
          <span>•</span>
          <span>{{ formatDate(article.createdAt) }}</span>
          <span>•</span>
          <span>{{ article.readTime }} min read</span>
        </div>
      </div>

      <div class="article-image">
        <img :src="article.imageUrl || 'https://via.placeholder.com/1200x600'" alt="Article image">
      </div>

      <div class="article-content" v-html="article.content"></div>

      <div class="article-actions">
        <button class="like-button" @click="likeArticle">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" :class="{'liked': isLiked}">
            <path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"></path>
          </svg>
          {{ article.likeCount }}
        </button>
        <div class="share-buttons">
          <button>Share</button>
        </div>
      </div>

      <div class="author-info">
        <img :src="article.authorAvatar || 'https://via.placeholder.com/100'" alt="Author avatar">
        <div class="author-details">
          <h3>{{ article.author }}</h3>
          <p>{{ article.authorBio }}</p>
        </div>
      </div>

      <div class="comments-section">
        <h2>Comments ({{ article.commentCount }})</h2>
        <div class="comment-form" v-if="isLoggedIn">
          <textarea v-model="newComment" placeholder="Write your comment..."></textarea>
          <button @click="postComment">Post Comment</button>
        </div>
        <div class="comments-list">
          <div v-for="comment in article.comments" :key="comment.id" class="comment">
            <img :src="comment.userAvatar || 'https://via.placeholder.com/50'" alt="User avatar">
            <div class="comment-content">
              <div class="comment-header">
                <h4>{{ comment.username }}</h4>
                <span>{{ formatDate(comment.createdAt) }}</span>
              </div>
              <p>{{ comment.content }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useArticleStore } from '../store/articleStore';
import { useUserStore } from '../store/userStore';

const route = useRoute();
const articleStore = useArticleStore();
const userStore = useUserStore();
const articleId = route.params.id;
const article = ref(null);
const loading = ref(true);
const error = ref(null);
const newComment = ref('');
const isLiked = ref(false);
const isLoggedIn = userStore.isAuthenticated;

onMounted(() => {
  fetchArticle();
});

const fetchArticle = async () => {
  try {
    loading.value = true;
    const data = await articleStore.fetchArticleById(articleId);
    article.value = data;
    // 模拟是否已点赞
    isLiked.value = Math.random() > 0.5;
  } catch (err) {
    error.value = 'Failed to load article';
    console.error('Failed to load article:', err);
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

const likeArticle = async () => {
  if (!isLoggedIn) {
    // 在实际应用中，这里应该跳转到登录页面
    alert('Please login to like articles');
    return;
  }

  try {
    await articleStore.likeArticle(articleId);
    isLiked.value = !isLiked.value;
    article.value.likeCount = isLiked.value ? article.value.likeCount + 1 : article.value.likeCount - 1;
  } catch (err) {
    console.error('Failed to like article:', err);
    alert('Failed to like article');
  }
};

const postComment = async () => {
  if (!newComment.value.trim()) {
    alert('Comment cannot be empty');
    return;
  }

  try {
    // 在实际应用中，这里应该调用API发布评论
    const newCommentObj = {
      id: Date.now(),
      username: userStore.currentUser.username,
      userAvatar: 'https://via.placeholder.com/50',
      content: newComment.value,
      createdAt: new Date().toISOString()
    };

    // 模拟添加评论
    if (!article.value.comments) {
      article.value.comments = [];
    }
    article.value.comments.push(newCommentObj);
    article.value.commentCount++;
    newComment.value = '';
  } catch (err) {
    console.error('Failed to post comment:', err);
    alert('Failed to post comment');
  }
};
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.loading,
.error {
  text-align: center;
  padding: 2rem;
}

.error {
  color: red;
}

.article-detail {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.article-header {
  padding: 1.5rem;
  text-align: center;
}

.category {
  display: inline-block;
  background-color: #f0f0f0;
  color: #333;
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.85rem;
  margin-bottom: 0.75rem;
}

.article-header h1 {
  font-size: 2rem;
  margin: 0 0 1rem 0;
}

.meta {
  color: #666;
  font-size: 0.9rem;
  display: flex;
  justify-content: center;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.article-image img {
  width: 100%;
  height: auto;
  max-height: 500px;
  object-fit: cover;
}

.article-content {
  padding: 2rem;
  line-height: 1.8;
}

.article-content h2,
.article-content h3 {
  margin-top: 1.5rem;
  margin-bottom: 1rem;
}

.article-content p {
  margin-bottom: 1rem;
}

.article-actions {
  padding: 0 2rem 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.like-button {
  background: none;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #666;
}

.like-button.liked {
  color: #ff4d4f;
}

.share-buttons button {
  background: none;
  border: 1px solid #ddd;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
}

.author-info {
  padding: 2rem;
  display: flex;
  align-items: center;
  gap: 1.5rem;
  border-bottom: 1px solid #eee;
}

.author-info img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.author-details h3 {
  margin: 0 0 0.5rem 0;
}

.author-details p {
  color: #666;
  margin: 0;
}

.comments-section {
  padding: 2rem;
}

.comments-section h2 {
  margin-top: 0;
  margin-bottom: 1.5rem;
}

.comment-form {
  margin-bottom: 2rem;
}

.comment-form textarea {
  width: 100%;
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  min-height: 100px;
  margin-bottom: 1rem;
}

.comment-form button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.comment {
  display: flex;
  gap: 1rem;
}

.comment img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.comment-header h4 {
  margin: 0;
  font-size: 1rem;
}

.comment-header span {
  color: #666;
  font-size: 0.85rem;
}

.comment p {
  margin: 0;
  color: #444;
}
</style>